//
//  ViewController.m
//  17-通讯录数据持久化
//
//  Created by dllo on 16/8/5.
//  Copyright © 2016年 YMJ. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) NSString *filePath;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.edgesForExtendedLayout = 0;
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableViewCell];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    [self cd];
}


#pragma mark - dataSource
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (UITableViewCellEditingStyle )tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 多选转态
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"多选状态打开");
    }
}
// 删除和添加
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [_arr removeObjectAtIndex:indexPath.row];
        BOOL isOk = [NSKeyedUnarchiver unarchiveObjectWithFile:_filePath];
        if (isOk) {
            BOOL isBetter = [NSKeyedArchiver archiveRootObject:_arr toFile:_filePath];
            if (isBetter) {
                NSLog(@"删除成功");
            } else {
                NSLog(@"删除失败");
            }
        }
        [tableView reloadData];

    }];
    UITableViewRowAction *rowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"添加" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"准备添加联系人");
        AddClassmatesViewController *addVC = [[AddClassmatesViewController alloc] init];
        [self.navigationController pushViewController:addVC animated:YES];
        addVC.block = ^(NewContacter * ymj_newContact) {
            if (ymj_newContact.name.length != 0) {
                [_arr insertObject:ymj_newContact atIndex:0];

            }
            
            
        };
        
        
    }];
   
    return @[rowAction,rowAction1];
}
- (void)cd {
    // doc路径
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    self.filePath = [docPath stringByAppendingPathComponent:@"tongxulu.plist"];
    NSLog(@"%@",_filePath);
    // 接档出的数组里面放的就是对象,别forin字典了
    NSArray *archiveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:_filePath];
    if (archiveArray.count != 0) {
        _arr = [NSMutableArray arrayWithArray:archiveArray];
    } else {
        
        NSArray *dataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DLS160710" ofType:@"plist"]];
        BOOL isOk =[NSKeyedArchiver archiveRootObject:dataArray toFile:_filePath];
        if (isOk) {
            NSLog(@"持久化成功");
        } else {
            NSLog(@"持久化失败");
        }
        _arr = [NSMutableArray array];
        for (NSDictionary *dic in dataArray) {
            NewContacter *mate = [NewContacter new];
            [mate setValuesForKeysWithDictionary:dic];
            [_arr addObject:mate];
        }
    }

    
    
}
// 联系人详情,修改
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 如果数组里有新添加的联系人
    if ([[_arr[indexPath.row] picStr] length] != 0) {
        AddClassmatesViewController *add =[[AddClassmatesViewController alloc] init];
        add.nextMate = _arr[indexPath.row];
        // block 回调
        add.block = ^ (NewContacter *mate) {
            // 如果修改了
            if (![mate.name isEqualToString:[_arr[indexPath.row] name]] || ![mate.contact isEqualToString:[_arr[indexPath.row] contact]] || ![mate.addresss isEqualToString:[_arr[indexPath.row] addresss]]) {
                [_arr removeObjectAtIndex:indexPath.row];
                [_arr insertObject:mate atIndex:indexPath.row];
            }
            
        };
        [self.navigationController pushViewController:add animated:YES];
    } else {
        NextViewController *next = [NextViewController new];
        next.nextMate = _arr[indexPath.row];
        // block 回调
        next.block = ^ (NewContacter *mate) {
            // 如果修改了
            if (![mate.name isEqualToString:[_arr[indexPath.row] name]] || ![mate.gender isEqualToString:[_arr[indexPath.row] gender]] || ![mate.phoneNumber isEqualToString:[_arr[indexPath.row] phoneNumber]] || ![[mate.age description] isEqualToString:[[_arr[indexPath.row] age] description]]) {
                [_arr removeObjectAtIndex:indexPath.row];
                [_arr insertObject:mate atIndex:indexPath.row];
            }
            
        };
        [self.navigationController pushViewController:next animated:YES];
    }

    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCell];
    cell.textLabel.text = [_arr[indexPath.row] name];
    return cell;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [_tableView reloadData];
    BOOL isOk = [NSKeyedUnarchiver unarchiveObjectWithFile:_filePath];
    if (isOk) {
        [NSKeyedArchiver archiveRootObject:_arr toFile:_filePath];
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
